'''
Case Type: 故障&可靠性测试
Case Name:  主节点故障	临时表操作过程中dn主故障
Create At: 2020/07/02
@zou_jialiang0505328114
Descption:
步骤 1.启动数据库
步骤 2.开始执行dml操作
步骤 3.执行dml操作期间kill主进程
步骤 4.重启主节点并检查状态
'''
import sys
import time
import unittest
from yat.test import Node
from yat.test import macro

sys.path.append(sys.path[0] + "/../")
from testcase.utils.Logger import Logger
from testcase.utils.Constant import Constant
from testcase.utils.Common import Common
from testcase.utils.CommonSH import *
from testcase.utils.ComThread import *


class IndexFileDamaged(unittest.TestCase):
    sh = CommonSH()
    nodes_tuple = ('PrimaryDbUser', 'Standby1DbUser', 'Standby2DbUser')

    @RestartDbCluster(*nodes_tuple)
    def setUp(self):
        self.log = Logger()
        self.log.info('------------Opengauss_Reliability_Dbsys_Case001.py start------------')
        self.DN1_PATH = macro.DB_INSTANCE_PATH
        self.dbUserNode = Node(node='dbuser')
        self.rootNode = Node()
        self.com = Common()
        self.Constant = Constant()
        self.t_name = 't_test'
        self.t_index_name = 't_test_index'

    def test_Index_file_damaged(self):
        # 新建表
        self.log.info('----------------------------创建表，并写入数据-----------------------------')
        msg = self.com.createLargeNumTable(self.dbUserNode, self.t_name, 1, 1000000)
        self.log.info(msg)

        insert_sql = f"insert into {self.t_name} values (1,'aaa');"

        test_thread = ComThread(self.sh.cycle_exec_sql, args=(insert_sql, 1000,))
        test_thread.setDaemon(True)
        test_thread.start()

        self.log.info('开始执行dml操作')

        time.sleep(5)

        self.log.info('执行dml操作期间kill主进程')

        msg = self.com.kill_pid(self.rootNode, 9)
        self.log.info(msg)
        self.assertEqual(msg, '')

        time.sleep(5)

        self.log.info('重启主节点并检查状态')
        is_started = self.sh.startDbCluster()
        self.assertTrue(is_started)

    def tearDown(self):
        # 清理环境，删除表
        msg = self.com.createLargeNumTable(self.dbUserNode, self.t_name, del_sign=True)
        self.log.info(msg)
        self.log.info('-------------Opengauss_Reliability_Dbsys_Case001:用例执行完毕--------------')
